package smcms.service.sso.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import smcms.commons.api.entity.result.CommonsResult;
import smcms.service.sso.entity.*;
import smcms.service.sso.mapper.AccountMapper;
import smcms.service.sso.service.UserLoginService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class UserLoginServiceImpl implements UserLoginService {
    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private CommonsResult commonsResult;
    @Override
    public List<SysMenuResp> hasMenu(String username) {
        List<SysMenuResp> sysMenuResps = accountMapper.hasMenu(username);

        return sysMenuResps;
    }

    @Override
    @Transactional
    public void UserRegister(AccountReq accountReq) {
        String userId = UUID.randomUUID().toString();
        String cloudId = UUID.randomUUID().toString();
        accountReq.setCloudId(cloudId);
        accountReq.setAccountId(userId);
        accountMapper.userRegister(accountReq);
        UserRoleRel userRoleRel = new UserRoleRel();
        userRoleRel.setUserId(userId);
        userRoleRel.setRoleId("1");
        accountMapper.grantRole(userRoleRel);
        CloudInfoReq cloudInfoReq = new CloudInfoReq();

        cloudInfoReq.setCloudId(cloudId);
        cloudInfoReq.setOwner(accountReq.getUsername());
        cloudInfoReq.setCorporationName(accountReq.getCorporationName());
        accountMapper.addCloud(cloudInfoReq);
    }

    @Override
    public StaffInfoResp getUserInfo(String username) {
        if (ObjectUtils.isEmpty(username)) {
            throw new IllegalArgumentException("非法参数异常");
        }
        StaffInfoReq staffInfoReq = new StaffInfoReq();
        staffInfoReq.setUsername(username);
        StaffInfoResp userInfo = accountMapper.getUserInfo(staffInfoReq);
        return userInfo;
    }

    @Override
    public CommonsResult updateUserInfo(StaffInfoReq staffInfoReq) {
        if (ObjectUtils.isEmpty(staffInfoReq.getUsername())) {
            return commonsResult.failed("更新账号不能为空");
        }
        accountMapper.updateUserInfo(staffInfoReq);
        return commonsResult.success("保存成功");
    }

    @Override
    public PageInfo<StaffInfoResp> queryStaffList(StaffInfoReq staffInfoReq) {
        if (StringUtils.isEmpty(staffInfoReq.getUsername())) {
            throw new IllegalArgumentException("用户名不能为空！");
        }
        int pageSize = staffInfoReq.getPageSize() == 0 ? 10 : staffInfoReq.getPageSize();
        int pageNum = staffInfoReq.getPageNum() == 0 ? 1 : staffInfoReq.getPageNum();
        ArrayList<String> username = new ArrayList<>();
        username.add(staffInfoReq.getUsername());
        List<StaffInfoResp> staffInfoResps = serchAllStaff(username,new ArrayList<StaffInfoResp>());
        if (!ObjectUtils.isEmpty(staffInfoReq.getStaffName())) {
            staffInfoResps = staffInfoResps.stream().
                    filter(e -> e.getStaffName().contains(staffInfoReq.getStaffName())
                    ).collect(Collectors.toList());
        }
        if (!ObjectUtils.isEmpty(staffInfoReq.getAccount())) {
            staffInfoResps = staffInfoResps.stream().
                    filter(e -> e.getAccount().contains(staffInfoReq.getAccount())
                    ).collect(Collectors.toList());
        }
        if (!ObjectUtils.isEmpty(staffInfoReq.getStaffPhone())) {
            staffInfoResps = staffInfoResps.stream().
                    filter(e -> e.getStaffPhone().contains(staffInfoReq.getStaffPhone())
                    ).collect(Collectors.toList());
        }
        if (!ObjectUtils.isEmpty(staffInfoReq.getStatus())) {
            staffInfoResps = staffInfoResps.stream().
                    filter(e -> e.getStatus().equals(staffInfoReq.getStatus())
                    ).collect(Collectors.toList());
        }
        if (!ObjectUtils.isEmpty(staffInfoReq.getEmpStartTime())&&!ObjectUtils.isEmpty(staffInfoReq.getEmpEndTime())) {
            staffInfoResps = staffInfoResps.stream().
                    filter(e -> {
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                        Date employeeTime = null;
                        Date startTime = null;
                        Date endTime = null;
                        try {
                            employeeTime = df.parse(e.getEmployeeTime());
                            startTime = df.parse(staffInfoReq.getEmpStartTime());
                            endTime = df.parse(staffInfoReq.getEmpEndTime());
                        } catch (ParseException ex) {
                            ex.printStackTrace();
                        }
                        if (employeeTime.getTime() >= startTime.getTime()
                                && employeeTime.getTime() <= endTime.getTime()) {
                            return true;
                        }return false;
                    })
                    .collect(Collectors.toList());
        }
//        StaffInfoResp self = accountMapper.getUserInfo(staffInfoReq);
//        staffInfoResps.add(self);
        PageInfo<StaffInfoResp> pageInfo = new PageInfo<>();
        pageInfo.setList(staffInfoResps);
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        pageInfo.setPages(staffInfoResps.size()/pageSize + 1);
        pageInfo.setTotal(staffInfoResps.size());
        pageInfo.setSize(staffInfoResps.size());
        return pageInfo;
    }

    @Override
    public List<StaffInfoResp> getStaffListByRole(StaffInfoReq staffInfoReq) {
        if (StringUtils.isEmpty(staffInfoReq.getUsername())) {
            throw new IllegalArgumentException("用户名不能为空！");
        }
        if (StringUtils.isEmpty(staffInfoReq.getRoleName())) {
            throw new IllegalArgumentException("角色名不能为空！");
        }
        ArrayList<String> username = new ArrayList<>();
        username.add(staffInfoReq.getUsername());
        List<StaffInfoResp> staffInfoResps = serchAllStaff(username,new ArrayList<StaffInfoResp>());
        List<StaffInfoResp> staffInfoList = staffInfoResps.stream().filter(staffInfoResp -> staffInfoResp.getRoleName().equals(staffInfoReq.getRoleName())).collect(Collectors.toList());
        StaffInfoResp self = accountMapper.getUserInfo(staffInfoReq);
        staffInfoResps.add(self);
        return staffInfoList;
    }

    private List<StaffInfoResp> serchAllStaff(List<String> accountList, List<StaffInfoResp> staffInfoResps){
        if (accountList.isEmpty()) {
            return staffInfoResps;
        }
        List<StaffInfoResp> staffList = accountMapper.getStaffList(accountList);
        if (staffList.isEmpty()) {
            return staffInfoResps;
        }
        ArrayList<String> newStaff = new ArrayList<>();
        staffList.forEach(staff ->{
            newStaff.add(staff.getAccount());
        });
        staffInfoResps.addAll(staffList);
        serchAllStaff(newStaff, staffInfoResps);
        return staffInfoResps;
    }
}
